package com.gao.api.gate.quick.tt;

import io.netty.channel.Channel;

import java.time.Duration;

/**
 * <p>
 * 可复用
 * </p>
 *
 * @author gaoshuangwen
 * @since 2022/02/12 14:34
 */
public class TimeToLiveChannel {
    private final Channel channel;
    private final long created;
    private long updated;
    private final Duration maxIdleTime;
    private final Duration maxLifeTime;

    public TimeToLiveChannel(Channel channel, Duration maxIdleTime, Duration maxLifeTime) {
        this.channel = channel;
        this.maxIdleTime = maxIdleTime;
        this.maxLifeTime = maxLifeTime;
        this.created = System.currentTimeMillis();
    }

    public boolean isEvict() {
        if (maxLifeTime != null) {
            if (created + maxLifeTime.toMillis() <= System.currentTimeMillis()) {
                return true;
            }
        }
        if(maxIdleTime == null){
            return false;
        }
        long ttl = updated - created;

        return maxIdleTime.toMinutes() <= ttl;
    }

    public Channel getChannel() {
        return channel;
    }

    public void updated(long updated) {
        this.updated = updated;
    }
}
